#!/usr/bin/env python
#coding=utf-8

import time
import skyservice
#icepypath = '../Ice-3.1.1/python'
#icepath = '../Ice-3.1.1'
#sys.path.insert(0, icepypath)


#import Ice, IcePy
#import Ice_Current_ice
#Ice.loadSlice('--all -I../ice-3.2.0/slice/Ice .\\skysec.ice')
#import Sky


class EvictorEntry():

    def __init__(self, id, servant, pos = 0):
        self.id_ = id
        self.servant_ = servant
        self.pos_ = pos
        #self.useCount_ = useCount


class SkyEvictor():
    def __init__(self):
        self.size = 1000
        self.loginMap = {}
        self.loginMapQuery = {}
        self.evictorMap = {}
        self.evictorQueue = []
        #self.evictorMutex         

#===============================================================================
#    def isSessActive(self, session):
#        if session not in self.loginMap:
#            return False
#        else:
#            return True
#        
#    def isIdActive(self, id):
#        if id not in self.loginMapQuery:
#            return False
#        else:
#            return True
#===============================================================================
    
    def getSession(self, id, deviceInfo):
        return id + deviceInfo    
    def login(self, id, deviceInfo):
        if id not in self.loginMapQuery:
            session = self.getSession(id, deviceInfo)
            modifyTime = int(time.time())
            self.loginMap.setdefault(session, [id, modifyTime, deviceInfo])
            deviceInfoMap = {}
            deviceInfoMap.setdefault(deviceInfo, session)
            self.loginMapQuery.setdefault(id, deviceInfoMap)
            return session
        else: 
            if deviceInfo in self.loginMapQuery[id]:
                modifyTime = int(time.time())
                session = self.loginMapQuery[id][deviceInfo]
                self.loginMap[session] = [id, modifyTime, deviceInfo]
                return session
            else:
                session = self.getSession(id, deviceInfo)
                self.loginMapQuery[id].setdefault(deviceInfo, session)
                modifyTime = int(time.time())
                self.loginMap.setdefault(session, [id, modifyTime, deviceInfo])
                return session
    
    def locate(self, session):
        entry_ = None
        
        if session not in self.loginMap:
            raise 'The User is InActive!\n'
        
        currTime = int(time.time())
        if currTime - self.loginMap[session][1] > 600:
            self.finished(session)
            raise 'The User is InActive!\n'
        
        id = self.loginMap[session][0]
        
        #step 3：
        if self.evictorMap.has_key(id):
            entry_ = self.evictorMap[id]
            print entry_
            print self.evictorQueue
            self.evictorQueue.remove(entry_.pos_)
            self.evictorQueue.append(entry_)
            entry_.pos_ = self.evictorQueue[-1]
        else:
            entry_ = EvictorEntry(id=id
                                  , servant=self.add(id) )    
            self.evictorMap.setdefault(id, entry_)
            self.evictorQueue.append(entry_)
            entry_.pos_ = self.evictorQueue[-1]
            print entry_.pos_
            self.evictServants()
        
        modifyTime = int(time.time())
        deviceInfo = self.loginMap[session][2]
        self.loginMap[session] = [id, modifyTime, deviceInfo]  
        return entry_.servant_
    
    def evictServants(self):
        eraseNum = len(self.evictorMap) - self.size
        if eraseNum < 1:
            return
        else:          
            for i in range(eraseNum):
                del self.evictorMap[self.evictorQueue[0].id_]
                self.evictorQueue.remove(0)                         
    
    
    def finished(self, session):
        id = self.loginMap[session][0]
        deviceInfo = self.loginMap[session][2]
        del self.loginMapQuery[id][deviceInfo]
        if len(self.loginMapQuery[id]) == 0:
            del self.loginMapQuery[id]
        del self.loginMap[session]
        return True
        
    def deactivate(self):
        self.size = 1
        self.evictServants()
        
    def add(self, id):
        obj = skyservice.SkyPimManager(id)
        return obj
    
#if __name__ == "__main__":
#    locator = SkyEvictor()
#    locator.login('skyUser0', 'xxx')
#    locator.login('skyUser0', 'xxx')
#    locator.login('skyUser0', 'yyy')
#    locator.login('skyUser1', 'yyy')
#    locator.login('skyUser1', 'xxx')
#    locator.login('skyUser1', 'zzz')
#    locator.finished('skyUser0xxx')
#    locator.finished('skyUser0yyy')
#    print locator.loginMap
#    print locator.loginMapQuery
#    print len(locator.loginMap)
#    print len(locator.loginMapQuery)

